package faac.http.MainPage;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import faac.Manager;
import faac.modules.chat.ChatCommandProc;



/**
 *
 * @author -D@@G-
 */
public class user_auth_props_in extends MainPageServletActions{


    /**
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @Override
    @SuppressWarnings("unchecked")
public String perform(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String ns = request.getParameter("ns"); // Имя сервиса
        if (!Manager.getInstance().getServiceNames().contains(ns)) {
            return "/main?page=error&id=0&ret=index";
        }
// String save = request.getParameter("save");


String[] gr = Manager.getInstance().getService(ns).getProps().getStringProperty("auth.groups").split(";");
        Set<String> au = ((ChatCommandProc)Manager.getInstance().getService(ns).cmd).getAuthObjects().keySet();
        HashSet[] grs = new HashSet[gr.length];
        for(int i=0; i<gr.length; i++){
            grs[i] = new HashSet<String>();
            try {
                String[] s = Manager.getInstance().getService(ns).getProps().getStringProperty("auth.group_"+gr[i]).split(";");
                if(s.length>0) {
                    for (int j = 0; j < s.length; j++) {
                        grs[i].add(s[j]);
                    }
                }
            } catch (Exception ex) {}
        }
        for(int i=0; i<gr.length; i++){
            for(String s:au){
                boolean b = getBoolVal(request, gr[i] + "_" + s);
                if(b && !grs[i].contains(s)) {
                    grs[i].add(s);
                }
                else if(!b && grs[i].contains(s)) {
                    grs[i].remove(s);
                }
            }
        }
        for(int i=0; i<gr.length; i++){
            String s = "";
            for(Object c:grs[i]){
                s += c.toString() + ";";
            }
            s = s.substring(0, s.length()-1);
            Manager.getInstance().getService(ns).getProps().setStringProperty("auth.group_"+gr[i], s);
        }
        Manager.getInstance().getService(ns).getProps().save();
    

        return "/main?page=message&id=0&ret=index";
    
    

}
}

